﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Security.Cryptography;
using ClassLibraryDatabase;


namespace ClassLibraryBaseClass
{
	public class UserModify
	{
		private int m_m_sID;                                   //ID 
		private String m_sUserName;                           //用户名
		private String m_sType;                               //用户类型
		private DateTime m_dateReg;                           //注册用户时间
		private DateTime m_dateBirthday;                      //出生日期       
		private String m_nSex;                                //性别
		private String m_sEmail;                              //电子邮箱
		private String m_sTelNumber;                          //电话号码
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="UserName"></param>
		/// <param name="dateReg"></param>
		/// <param name="Sex"></param>
		/// <param name="dateBirthday"></param>
		/// <param name="Email"></param>
		/// <param name="TelNumber"></param>
		public UserModify(int nID, String UserName, String Type, DateTime dateReg, DateTime dateBirthday, String Sex, String Email, String TelNumber)
		{
			m_m_sID = nID;
			m_sUserName = UserName;
			m_sType = Type;
			m_dateReg = dateReg;
			m_dateBirthday = dateBirthday;
			m_nSex = Sex;
			m_sEmail = Email;
			m_sTelNumber = TelNumber;
		}
		public UserModify(String UserName, String Type, DateTime dateReg, DateTime dateBirthday, String Sex, String Email, String TelNumber)
		{
			m_m_sID = -1;
			m_sUserName = UserName;
			m_sType = Type;
			m_dateReg = dateReg;
			m_dateBirthday = dateBirthday;
			m_nSex = Sex;
			m_sEmail = Email;
			m_sTelNumber = TelNumber;
		}
		public UserModify()
		{
			m_m_sID = 0;                               //ID 
			m_sUserName = "";                           //用户名
			m_dateReg = new DateTime();               //注册用户时间
			m_nSex = "";                                    //性别
			m_dateBirthday = new DateTime();         //出生日期
			m_sEmail = "";                              //电子邮箱
			m_sTelNumber = "";                          //电话号码
		}
		/*********************相应的8个属性************************/
		public int ID
		{
			get
			{
				return m_m_sID;
			}
		}
		public string UserName
		{
			get
			{
				return m_sUserName;
			}
		}
		public string Type
		{
			get
			{
				return m_sType;
			}
			set
			{
				m_sType = value;
			}
		}
		public DateTime dateReg
		{
			get
			{
				return m_dateReg;
			}

		}
		public String Sex
		{
			get
			{
				return m_nSex;
			}
			set
			{
				m_nSex = value;
			}
		}
		public DateTime dateBirthday
		{
			get
			{
				return m_dateBirthday;
			}
			set
			{
				m_dateBirthday = value;
			}
		}
		public String Email
		{
			get
			{
				return m_sEmail;
			}
		}
		public String TelNumber
		{
			get
			{
				return m_sTelNumber;
			}
			set
			{
				m_sTelNumber = value;
			}
		}
		/*****************************************添加、删除、保存和创建用户方法********************************************/
		/// <summary>
		/// 添加一个用户至数据库,类实例生成之前
		/// </summary>
		/// <param name="ID"></param>
		/// <param name="用户名"></param>
		/// <param name="注册时间"></param>
		/// <param name="性别"></param>
		/// <param name="生日"></param>
		/// <param name="邮件地址"></param>
		/// <param name="电话号码"></para m>
		public static bool AddUser(String username, String type, DateTime reg, DateTime birthday, String sex, String email, String telnumber, string password)
		{
			UserModify user = new UserModify(username, type, reg, birthday, sex, email, telnumber);
			return user.AddUser(password);
		}
		public User GetUser()
		{
			return new User(m_m_sID, m_sUserName);
		}
		/// <summary>
		/// 添加一个用户至数据库
		/// </summary>
		public bool AddUser(string password)
		{
			int nT = 0;
			if (this.m_sType != null)
				++nT;
			if (this.dateBirthday != null)
				++nT;
			if (this.TelNumber != null)
				++nT;
			nT += 4;
			string[] name = new string[nT];
			object[] value = new object[nT];
			name[0] = "UserName";
			value[0] = this.UserName;

			name[1] = "RegDate";
			value[1] = DateTime.Today;

			name[2] = "Sex";
			value[2] = this.Sex;

			name[3] = "Email";
			value[3] = this.Email;
			nT = 3;
			if (this.m_sType != null)
			{
				name[++nT] = "Type";
				value[nT] = Type;
			}
			if (this.dateBirthday != null)
			{
				name[++nT] = "Birthday";
				value[nT] = dateBirthday;
			}
			if (this.TelNumber != null)
			{
				name[++nT] = "TelNumber";
				value[nT] = TelNumber;
			}
			try
			{
				bool bT = DataBaseClass.insertData(name, value, "MovieUser", DataBaseClass.GetConnectionString());
				if (bT)
				{
					DataBaseClass.insertData("INSERT Password (UserName , Password) VALUES ('" + this.UserName + "','" + GetMD5(password) + "')", DataBaseClass.GetConnectionString());
					this.m_m_sID = DataBaseClass.GetMaxID("MovieUser", DataBaseClass.GetConnectionString());
				}
				return bT;
			}
			catch (SqlException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (Exception e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return false;
			}
		}
		/// <summary>
		/// 从数据库删除一个用户
		/// </summary>
		/// <param name="?"></param>
		static bool DeleteUser(UserModify user)
		{
			DataBaseClass.deleteData("DELETE Order WHERE UserID=" + user.ID, DataBaseClass.GetConnectionString());
			List<MComment> mList = MComment.GetListFromDataTable(DataBaseClass.selectData("SELECT * FROM M_Comment WHERE UserID=" + user.ID, DataBaseClass.GetConnectionString()));
			foreach (MComment comment in mList)
			{
				comment.DelM_Comment();
			}
			List<TComment> tList = TComment.GetListFromDataTable(DataBaseClass.selectData("SELECT * FROM T_Comment WHERE UserID=" + user.ID, DataBaseClass.GetConnectionString()));
			foreach (TComment comment in tList)
			{
				comment.DelT_Comment();
			}
			List<Mail> maList = Mail.GetListFromDataTable(DataBaseClass.selectData("SELECT * FROM Mail WHERE RecieverID=" + user.ID, DataBaseClass.GetConnectionString()));
			foreach (Mail mail in maList)
			{
				mail.DelMa_SelfItem();
			}
			List<Favorites> fList = Favorites.GetListOfFavoritesByDatatable(DataBaseClass.selectData("SELECT * FROM Favourites WHERE UserID=" + user.ID, DataBaseClass.GetConnectionString()));
			foreach (Favorites favorites in fList)
			{
				favorites.DeleteFavoriteMovie();
			}
			try
			{
				DataBaseClass.deleteData("DELETE PassWord WHERE UserName='" + user.UserName + "'", DataBaseClass.GetConnectionString());
				return DataBaseClass.deleteData("ID", user.ID, "MovieUser", DataBaseClass.GetConnectionString());
			}
			catch (SqlException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (Exception e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return false;
			}
			//return DataBaseClass.deleteData("ID", user.ID, "MovieUser", DataBaseClass.GetConnectionString());
		}
		/// <summary>
		/// 创建一个上线的用户
		/// </summary>
		/// <param name="用户名"></param>
		/// <param name="密码"></param>
		/// <returns></returns>
		public static UserModify GetUser(String username, String password)
		{
			MD5 md5 = MD5.Create();//new MD5CryptoServiceProvider();
			byte[] sourse = System.Text.UnicodeEncoding.Default.GetBytes(password);
			byte[] result = md5.ComputeHash(sourse);
			string sResult = "";
			for (int i = 0; i < result.Length; i++)
			{
				// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符
				sResult += Convert.ToString(result[i], 16).PadLeft(2, '0'); ;

			}
			sResult.PadLeft(32, '0');
			String sql = "SELECT * FROM MovieUser WHERE UserName IN (SELECT UserName FROM Password WHERE UserName=" + username + " AND Password='" + sResult + "')";
			DataTable dataTable = DataBaseClass.selectData(sql, DataBaseClass.GetConnectionString());

			return GetUserByRow(dataTable.Rows[0]);
		}
		public static UserModify GetUser(int nID)
		{
			try
			{
				DataTable table = DataBaseClass.selectData("SELECT * FROM MovieUser WHERE ID=" + nID, DataBaseClass.GetConnectionString());
				if (table.Rows.Count == 0)
					return null;
				return GetUserByRow(table.Rows[0]);
			}
			catch (SqlException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			catch (Exception e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return null;
			}
		}
		public static UserModify GetUser(string name)
		{
			try
			{
				DataTable table = DataBaseClass.selectData("SELECT * FROM MovieUser WHERE UserName='" + name + "'", DataBaseClass.GetConnectionString());
				if (table.Rows.Count == 0)
					return null;
				return GetUserByRow(table.Rows[0]);
			}
			catch (SqlException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			catch (Exception e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return null;
			}
		}
		public static bool Del_UserModify(string name)
		{

			UserModify modify = UserModify.GetUser(name);
			return modify.Del_UserModify();
		}
		public bool Del_UserModify()
		{
			try
			{
				List<TComment> tList = TComment.GetListFromDataTable(this.GetUser().GetDataTableOfCommentOfTheatre());
				foreach (TComment comment in tList)
					comment.DelT_Comment();
			}
			catch (Exception e) { System.Console.WriteLine(e.Message); }

			try
			{
				List<MComment> mList = MComment.GetListFromDataTable(this.GetUser().GetDataTableOfCommentOfMovie());
				foreach (MComment comment in mList)
					comment.DelM_Comment();
			}
			catch (Exception e) { System.Console.WriteLine(e.Message); }

			try
			{
				List<Mail> maList = Mail.GetListFromDataTable(this.GetUser().GetDataTableOfLetter());
				foreach (Mail mail in maList)
					mail.DelMa_SelfItem();
			}
			catch (Exception e) { System.Console.WriteLine(e.Message); }

			try
			{
				List<Favorites> fList = Favorites.GetListOfFavoritesByDatatable(this.GetUser().GetDataTableOfFavorites());
				foreach (Favorites favorites in fList)
					favorites.DeleteFavoriteMovie();
			}
			catch (Exception e) { System.Console.WriteLine(e.Message); }

			try
			{
				DataBaseClass.deleteData("DELETE PassWord WHERE UserName='" + this.UserName + "'", DataBaseClass.GetConnectionString());

				return DataBaseClass.deleteData("ID", this.ID, "MovieUser", DataBaseClass.GetConnectionString());
			}
			catch (SqlException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (Exception e)
			{
				System.Console.Write("UserModify类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return false;
			}
		}
		public static UserModify GetUserByRow(DataRow row)
		{
			return new UserModify((int)row["ID"], row["UserName"] as string, row["Type"] as string, (DateTime)row["RegDate"], (DateTime)row["Birthday"], row["Sex"] as string, row["Email"] as string, row["TelNumber"] as string);
		}
		/// <summary>
		/// 保存对此用户的修改
		/// </summary>
		public void UpdateUser()
		{
			String sql = "UPDATE User SET";
			if (m_dateBirthday != null)
				sql += "Birthday='" + m_dateBirthday.ToString() + "',";
			if (m_sTelNumber != null)
				sql += "TelNumber='" + m_sTelNumber.ToString() + "',";
			sql += "m_nSex=" + m_nSex;
			sql += " WHERE ID=" + m_m_sID;
			DataBaseClass.Update(sql, DataBaseClass.GetConnectionString());
		}
		public static List<UserModify> GetListByDataTable(DataTable table)
		{
			List<UserModify> list = new List<UserModify>();
			foreach (DataRow row in table.Rows)
			{
				list.Add(GetUserByRow(row));
			}
			return list;
		}
		public static string GetMD5(string password)
		{
			MD5 md5 = MD5.Create();//new MD5CryptoServiceProvider();
			byte[] sourse = System.Text.UnicodeEncoding.Default.GetBytes(password);
			byte[] result = md5.ComputeHash(sourse);
			string sResult = "";
			for (int i = 0; i < result.Length; i++)
			{
				// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符
				sResult += Convert.ToString(result[i], 16).PadLeft(2, '0'); ;

			}
			sResult.PadLeft(32, '0');
			return sResult;
		}
	}

	public class Test7
	{
		public static void Test()
		{
			UserModify m = UserModify.GetUser("abc");
			if (m != null)
				m.Del_UserModify();
			UserModify modify = new UserModify(-1, "abc", "abc", DateTime.Today, DateTime.Today, "M", "asfd", "werwe");
			modify.AddUser("rasdfasd");
			modify = UserModify.GetUser("abc");
			if (modify == null)
				System.Console.WriteLine("GetUser错误");
			modify.Del_UserModify();
			modify = UserModify.GetUser(modify.ID);
			if (modify != null)
				System.Console.WriteLine("删除错误");
			modify = new UserModify(-1, "abc", "abc", DateTime.Today, DateTime.Today, "M", "asfd", "werwe");
			modify.AddUser("rasdfasd");
			MComment comment = new MComment(-1, modify.ID, 1, DateTime.Today, "", "");
			comment.UpdateM_Comment();
			TComment tc = new TComment(-1, modify.ID, 1, DateTime.Today, "", "");
			Mail mail = new Mail(-1, 1, modify.ID, DateTime.Today, "", "");
			mail.UpdateMail();
			Favorites f = new Favorites(modify.ID, 1);
			f.AddFavoriteMovie();
			modify.Del_UserModify();

		}
	}
}